package logic

import (
	"context"
	"github.com/jinzhu/copier"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentChildLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentChildLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentChildLogic {
	return AgentChildLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentChildLogic) AgentChild(req *types.AgentChildListReq) (resp *respx.PageResp, err error) {
	// todo: add your logic here and delete this line
	uid, err := requestx.FetchIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	if len(req.ParentUid) > 0 {
		subAgent, err2 := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: respx.IDParse(req.ParentUid).GetInt64()})
		if err2 != nil {
			return nil, err2
		}
		if subAgent.ParentUid != uid {
			return nil, errorx.NewDefaultError("你没有权限查看哦～")
		}
		uid = subAgent.Id
	}
	child, err := l.svcCtx.AgentRpc.AgentChild(l.ctx, &agentClient.AgentChildReq{
		Page:      req.Page,
		PageSize:  req.PageSize,
		ParentUid: uid,
	})
	data := make([]*types.AgentChildListResp, 0)
	for _, v := range child.List {
		var c types.AgentChildListResp
		err := copier.Copy(&c, v)
		if err != nil {
			continue
		}
		if len(v.RealName) > 0 {
			c.Name = v.RealName
		}
		c.Id = respx.IDFrom(v.Id).ToString()
		c.CreateTime = tools.TimeUnixShowLayoutString(v.CreateTime)
		data = append(data, &c)

	}
	if err != nil {
		return nil, err
	}
	return respx.NewPageResp(req.Page, req.PageSize, child.Total, data), nil
}
